package Test3;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UDPSender implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public UDPSender(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        while (true) {
            try {
                String msg = reader.readLine();
                byte[] data = msg.getBytes();
                DatagramPacket packet = new DatagramPacket(data, 0, data.length, new InetSocketAddress(toIP, toPort));

                //发送数据
                socket.send(packet);

                //断开连接条件
                if (msg.equals("bye")) break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //关闭连接
        socket.close();
    }
}
